﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aragorn.SOA.Infratructure.Config;
using Aragorn.SOA.Infratructure.Config;
using Org.Apache.Zookeeper.Data;
using ZooKeeperNet;

namespace Aragorn.SOA.Infratructure
{
    public class ServicesWatcher : IWatcher
    {
        private IZooKeeper zk;

       public static ZKConfig config =  new ZKConfig();
        public ServicesWatcher(IZooKeeper zookeeper)
        {
            this.zk = zookeeper;
        }

        public void Process(WatchedEvent @event)
        {

            Console.WriteLine("this is watcher!");

            if (@event.Type == EventType.NodeChildrenChanged)
            {
                Console.WriteLine("test is NodeChildrenChanged");
                Console.WriteLine(@event.Path);
            }
            if (@event.Type==EventType.NodeDataChanged)
            {
                Console.WriteLine("test is NodeDataChanged");
                Console.WriteLine(@event.Path);
            }
            if (@event.Type==EventType.NodeCreated)
            {
                Console.WriteLine("test is NodeCreated");
                Console.WriteLine(@event.Path);
            }


            


            //循环注册各服务监控节点的watcher
            List<string> swnodes = ServicesWatcher.GetServicesNames(zk);

             swnodes.ForEach(x =>
             {
                 zk.Exists(config.ZK_REGISTRY_PATH + "/" + x.ToString(), true);
             });            


        }


        public static List<string> GetServicesNames(IZooKeeper zk)
        {
            var host = new List<string>();


            zk.GetChildren(config.ZK_REGISTRY_PATH,null).ToList().ForEach(x =>
            {
                var alive = zk.GetChildren(config.ZK_REGISTRY_PATH + "/" + x, null).ToList();
                host = host.Union(alive).ToList();
            });

            return host;
        }
    }
}
 